function myPromise(executor){
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    let self = this;
    this.callbacks = [];
    function resolve(data){
        if(self.PromiseState !== 'pending') return;
        self.PromiseState = 'fulfilled';
        self.PromiseResult = data;
        self.callbacks.forEach(element => {
            element.onResolved(data);
        });
    }
    function reject(data){
        if(self.PromiseState !== 'pending') return;
        self.PromiseState = 'rejected';
        self.PromiseResult = data;
        self.callbacks.forEach(element => {
            element.onRejected(data);
        })
    }
    try{
        executor(resolve, reject);
    }
    catch(e){
        reject(e);
    }
}


myPromise.prototype.then = function(onResolved, onRejected){
    return new myPromise((resolve, reject) => {
        if(this.PromiseState === 'fulfilled'){   
            try{
                //获取回调函数的执行结果
                let result = onResolved(this.PromiseResult);
                
                //判断
                if(result instanceof myPromise){//如果是 Promise 类型的对象,我就将下一个promise结果赋予外层
                    result.then(v => {  resolve(v); },r=>{reject(r);})
                }else{resolve(result);}  //如果返回的不是promise对象,都将其赋予成功状态
            }catch(e){
                reject(e);	//如果出错了,则返回失败状态
            }
        }
        if(this.PromiseState === 'rejected'){ onRejected(this.PromiseResult);}
        //判断 pending 状态
        if(this.PromiseState === 'pending'){
            this.callbacks.push({ onResolved: onResolved, onRejected: onRejected});
        }
    })
}